import json
import os
from logging.config import dictConfig

from flask import Flask, request, Response, render_template, session, redirect, url_for

from ddtalk import DingTalk
from jms import delete_user
from ldap import LDAP
from message import SendMessage
from settings import LDAP_CONFIG, logger_dict

dictConfig(logger_dict)
server = Flask(__name__)
server.config['SECRET_KEY'] = os.urandom(24)


@server.route('/', methods=['GET'])
def default():
    """
    接口文档路由
    :return: 接口文档页面
    """
    if 'username' in session and 'password' in session:
        return render_template("apiDoc.html")
    return redirect(url_for('login'))


@server.route('/login', methods=['POST', 'GET'])
def login():
    """
    接口登陆路由，接口说明中会包含敏感信息，需要登陆访问
    :return: 登陆界面
    """
    if request.method == 'POST':
        user_info = request.form.to_dict()
        if user_info.get('username') == 'admin' and user_info.get('password') == 'senguo123':
            session['username'] = user_info.get('username')
            session['password'] = user_info.get('password')
            return redirect(url_for('default'))
    return render_template('login.html')


@server.route("/add_user", methods=['POST'])
def add():
    """
    新员工入职路由，将新入职员工添加到公司ldap数据库中。
    :return:
    """
    if request.method == "POST":
        # 获取新入职员工姓名与userid,岗位
        # print(request.json)
        username = request.json['name']
        userid = request.json['userid']
        position = request.json['position']
        # 获取所属项目组
        department_id = request.json['department']
        department_dict = DingTalk.get_department_list()
        parent_ids = DingTalk.get_parentIds(department_id[0])
        try:
            department = department_dict[parent_ids].replace('组', '')
        except:
            department = department_dict[parent_ids]
        # 将新员工加入ldap
        ldap = LDAP(**LDAP_CONFIG)
        res = ldap.add_user(userid, username=username, positions=position, department=department)
        log_info = {'type': "员工入职", "username": username, "position": position, "department": department,
                    "response": res}
        server.logger.info(log_info)
        if res is True:
            SendMessage(log_info)
            for dn_dict in ldap.get_user_department(username=username):
                if dn_dict.get("cn", "") != department:
                    ldap.delete_user(dn=dn_dict.get("dn", ""))
        return Response(json.dumps(log_info), content_type='application/json')
    else:
        log_info = {"type": "request", "response": "请求方法错误"}
        server.logger.info(log_info)
        return Response(json.dumps(log_info), content_type='application/json')


@server.route('/remove_user', methods=['POST'])
def remove():
    """
    员工离职路由，将已经离职的员工从公司的ldap数据库和JumpServer数据库中删除.
    :return:
    """
    if request.method == "POST":
        # 获取离职员工信息
        username = request.json['name']
        position = request.json['position']
        department_id = request.json['department']
        department_dict = DingTalk.get_department_list()
        parent_ids = DingTalk.get_parentIds(department_id)

        # 保证钉钉组织架构命名和ldap组织架构命名相同
        try:
            department = department_dict[parent_ids].replace('组', '')
        except:
            department = department_dict[parent_ids]
        # 将离职员工从ldap中删除
        ldap = LDAP(**LDAP_CONFIG)
        res = ldap.delete_user(username=username, positions=position, department=department)
        log_info = {'type': "员工离职", "username": username, "position": position, "department": department,
                    "response": res}
        server.logger.info(log_info)
        SendMessage(log_info)

        # 将员工从JumpServer中删除(删除数据库对应记录)
        delete_user(username, position)
        return Response(json.dumps(log_info), content_type='application/json')
    else:
        log_info = {"type": "request", "response": "请求方法错误"}
        return Response(json.dumps(log_info), content_type='application/json')


if __name__ == "__main__":
    server.run(port=9000, host='0.0.0.0')
